package com.water.camera.activity;

import static com.water.camera.util.Utils.convertViewToBitmap;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.widget.FrameLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.water.camera.App;
import com.water.camera.bean.MediaData;
import com.water.camera.fragment.BaseDialogFragment;
import com.water.camera.fragment.ProgressLoadingDlg;
import com.water.camera.mark.BaseMark;
import com.water.camera.util.SaveUtils;
import com.water.camera.util.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseSaveAct extends BaseActivity {

    boolean working = false;
    SilentTask task = null;
    ProgressLoadingDlg loadingDlg = null;
    ArrayList<String> output = new ArrayList<>();

    protected void showLoading(int num, String msg) {
        if (loadingDlg == null) {
            loadingDlg = new ProgressLoadingDlg().setMsg(msg);
            loadingDlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    loadingDlg = null;
                }
            });
        } else {
            return;
        }
        loadingDlg.setMax(num);
        loadingDlg.show(getSupportFragmentManager(), "");
    }

    @Override
    protected void hideLoading() {
        if (loadingDlg != null) {
            loadingDlg.dismiss();
        }
    }

    protected void updateProgress(int p) {
        if (loadingDlg != null) {
            loadingDlg.setProgress(p);
        }
    }

    protected void save(List<String> list) {
        showLoading(list.size(), "正在保存图片到相册");
        if (working) {
            return;
        }
        working = true;
        task = new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                try {
                    int i = 0;
                    for (String s : list) {
                        int j = ++i;
                        h.post(() -> updateProgress(j));
                        File f = new File(s);
                        if (f.exists()) {
                            SaveUtils.saveImgFileToAlbum(App.getApp(), s);
                        }
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    h.post(() -> {
                        working = false;
                        hideLoading();
                        finishSave();
                    });
                }
            }
        };
        TaskEngine.getInstance().submit(task);
    }

    protected void save(BaseMark waterMark, FrameLayout frame, List<MediaData> list) {
        showLoading(list.size(), null);
        if (working) {
            return;
        }
        working = true;
        output.clear();
        int[] tmp = new int[2];
        waterMark.getLocationOnScreen(tmp);
        int[] tmp2 = new int[2];
        frame.getLocationOnScreen(tmp2);

        float l = (tmp[0] - tmp2[0]) * 1f / frame.getWidth();
        float t = (tmp[1] - tmp2[1]) * 1f / frame.getHeight();
        float r = (waterMark.getWidth() * waterMark.getScale()) / frame.getWidth();

        task = new SilentTask("save") {
            @Override
            public void runInBackground() throws Exception {
                try {
                    int i = 0;
                    for (MediaData data : list) {
                        ++i;
                        final int j = i;
                        h.post(() -> updateProgress(j));
                        Bitmap bm = Glide.with(App.getApp()).asBitmap().load(data.getPath()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).submit().get();
                        Bitmap frontBitmap = convertViewToBitmap(waterMark);
                        float scale = bm.getWidth() * r / frontBitmap.getWidth();
                        frontBitmap = scaleBm(frontBitmap, scale);

                        Canvas canvas = new Canvas(bm);
                        int left = (int) (l * bm.getWidth());
                        int top = (int) (t * bm.getHeight());
                        Rect baseRect = new Rect(left, top, left + frontBitmap.getWidth(), top + frontBitmap.getHeight());
                        Rect frontRect = new Rect(0, 0, frontBitmap.getWidth(), frontBitmap.getHeight());
                        canvas.drawBitmap(frontBitmap, frontRect, baseRect, null);
                        File out = new File(getCacheDir(), System.currentTimeMillis() + ".jpg");

                        boolean bo = Utils.saveImageTo(bm, out.getAbsolutePath());

                        if (bo) {
                            output.add(out.getAbsolutePath());
                        }
                    }
                    h.post(() -> {
                        working = false;
                        hideLoading();
                        finishSave();
                    });
                } catch (Throwable e) {
                    h.post(() -> {
                        working = false;
                        hideLoading();
                        finishSave();
                    });
                }
            }
        };

        TaskEngine.getInstance().submit(task);
    }

    protected abstract void finishSave();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.cancel();
        }
    }

    private Bitmap scaleBm(Bitmap originalBitmap, float scaleRatio) {
        int originalWidth = originalBitmap.getWidth();
        int originalHeight = originalBitmap.getHeight();

        int scaledWidth = Math.round(originalWidth * scaleRatio);
        int scaledHeight = Math.round(originalHeight * scaleRatio);

        Bitmap scaledBitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, originalBitmap.getConfig());

        Matrix matrix = new Matrix();
        matrix.postScale(scaleRatio, scaleRatio);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(originalBitmap, matrix, null);
        originalBitmap.recycle();

        return scaledBitmap;
    }
}
